package com.prig.base.service;

import cn.hutool.core.util.StrUtil;
import com.prig.base.DTO.input.PageKeywordSortDto;
import com.prig.base.entity.Role;
import com.prig.base.repository.RoleRepository;
import com.prig.base.util.ChangeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.List;

@Service
public class RoleService {
    private RoleRepository roleRepository;
    @Autowired
    public void setRoleRepository(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }

    public Role saveRole(Role role){
        return roleRepository.save(role);
    }



    public List<Role> getRoles(long adminId){
        return roleRepository.findByAdminId(adminId);
    }

    public void delete(@NotBlank String ids) {
        roleRepository.deleteByIds(ChangeType.String2Long(ids));
    }

    public Role getRole(long roleId) {
        return roleRepository.getOne(roleId);
    }

    public Page<Role> getRoles(Long adminId, PageKeywordSortDto dto) {
        Pageable pageable = PageRequest.of(dto.getSQLPage(),dto.getLimit(), dto.getSort());
        return roleRepository.findByAdminId(adminId,pageable);
    }

    public List<Role> getRoles(){
        return roleRepository.findAll();
    }

    public Page<Role> getRoles(PageKeywordSortDto dto){
        Pageable pageable = PageRequest.of(dto.getSQLPage(),dto.getLimit(),dto.getSort());
        if (StrUtil.isNotBlank(dto.getKeyword())){
            dto.setKeyword("%"+dto.getKeyword()+"%");
            return roleRepository.findByDescriptionLikeOrRoleNameLike(dto.getKeyword(),dto.getKeyword(),pageable);
        }
        return roleRepository.findAll(pageable);
    }
}
